package service.impl;

import common.consts.Consts;
import common.consts.Offers;
import dao.OfferDao;
import dao.RatingDao;
import dao.RecruitmentDao;
import dao.UserDataProfileDao;
import domain.Offer;
import domain.Rating;
import domain.Recruitment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.RatingService;
import service.ServiceResponse;

import java.util.Date;
import java.util.List;

import static common.consts.Ratings.valueOf;

/**
 * Created by Administrator on 2015/7/3.
 */


@Service
public class RatingServiceImpl extends ServiceBase implements RatingService {
    private static final Logger LOGGER = LoggerFactory.getLogger(RatingServiceImpl.class);

    @Autowired
    private RecruitmentDao recruitmentDao;
    @Autowired
    private OfferDao offerDao;
    @Autowired
    private RatingDao ratingDao;
    @Autowired
    private UserDataProfileDao userDataProfileDao;

    @Override
    @Transactional(readOnly = false)
    public ServiceResponse rate2Employer(long rater, long ratee, long recruitmentId, String rate, String comment) {
        Recruitment recruitment = recruitmentDao.get(recruitmentId);
        ServiceResponse response = validateRecruitment(recruitment);
        if (response.isFailed()) {
            return response;
        }

        Offer offer = offerDao.queryByApplierAndRecruitmentId(rater, recruitmentId);
        response = validateOffer(offer, ratee);
        if (response.isFailed()) {
            return response;
        }

        //评价，rating表插入一条评价记录
        saveRate(rater, ratee, recruitmentId, rate, comment);

        // 更新 offer 的 rate_result
        offerDao.updateRateResult(offer.getId(), rate);
        return ServiceResponse.success();
    }

    @Override
    @Transactional(readOnly = true)
    public ServiceResponse getMyRateFromEmployer(long user) {
        //用户获取雇佣者对自己有关的评论信息。
        List<Rating> ratings = ratingDao.queryByApplier(user);
        ServiceResponse response = ServiceResponse.success().with("ratings",ratings);
        return response;
    }

    @Override
    @Transactional(readOnly = false)
    public ServiceResponse rate2User(long rater, long ratee, long recruitmentId, String rate, String comment) {
        //a. 判断当前招聘是否已经结束（根据work_end_time和当前日期比较），如果还没结束则不能评价
        Recruitment recruitment = recruitmentDao.get(recruitmentId);
        ServiceResponse response = validateRecruitment(recruitment);
        if (response.isFailed()) {
            return response;
        }

        //b. 判断target(ratee)用户是否有应聘了reviewer(rater)的工作  （从offer表查数据），如果没有则不能评价
        //根据应聘者id和recruitment查询offer
        Offer offer = offerDao.queryByApplierAndRecruitmentId(ratee, recruitmentId);
        response = validateOffer(offer, rater);
        if (response.isFailed()) {
            return response;
        }

        //评价，rating表插入一条评价记录
        saveRate(rater, ratee, recruitmentId, rate, comment);

        // 更新 offer 的 rate_result
        offerDao.updateRateResult(offer.getId(), rate);
        return ServiceResponse.success();
    }

    private ServiceResponse validateRecruitment(Recruitment recruitment) {
        if (recruitment == null) {
            return ServiceResponse.fail(Consts.i18nKey.UNKNOWN_RECRUITMENT);
        }
        //应该结束的时间
        Date workEndDate = recruitment.getWorkEndDate();
        //根据work_end_time和当前日期比较
        Date now = new Date();

        if (now.before(workEndDate)) {
            // 工作还没结束
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("工作还没结束，暂时不能评价");
            }
            return ServiceResponse.fail(Consts.i18nKey.CANNOT_RATING_DUE_TO_WORK_NOT_END);
        }
        return ServiceResponse.success();
    }

    private ServiceResponse validateOffer(Offer offer, long employer) {
        if (offer == null) {
            return ServiceResponse.fail(Consts.i18nKey.UNKNOWN_OFFER);

        }
        //判断雇主对不对
        if (offer.getEmployer() != employer) {
            //雇主不对
            return ServiceResponse.fail(Consts.i18nKey.RATEE_RECRUITMENT_TO_RATER_NOT_OK);
        }

        if (Offers.isWaiting(offer.getStatus()) || Offers.isCanceled(offer.getStatus())) {
            return ServiceResponse.fail(Consts.i18nKey.INVALID_OFFER_STATUS);

        }
        //插入一条评价之前，是否已经评价过了
        if (Offers.isRated(offer.getRateResult())) {
            return ServiceResponse.fail(Consts.i18nKey.EMPLOYEE_RATED);
        }
        return ServiceResponse.success();
    }

    private void saveRate(long rater, long ratee, long recruitmentId, String rate, String comment) {
        Rating r = new Rating();
        r.setRecruitment(recruitmentId);
        r.setRatee(ratee);
        r.setRater(rater);
        r.setRate(rate);
        r.setRateTime(new Date());
        r.setComment(comment == null ? "" : comment);
        ratingDao.insert(r);

        //评价完后，同步相关数据到评价者rater/被评价者ratee的user_data_profile
        switch (valueOf(rate)) {
            case FLOWER:
                userDataProfileDao.increaseSentFlower(rater);
                userDataProfileDao.increaseReceiveFlower(ratee);
                break;
            case EGG:
                userDataProfileDao.increaseSentEgg(rater);
                userDataProfileDao.increaseReceiveEgg(ratee);
                break;
        }
    }


    public void setRecruitmentDao(RecruitmentDao recruitmentDao) {
        this.recruitmentDao = recruitmentDao;
    }

    public void setOfferDao(OfferDao offerDao) {
        this.offerDao = offerDao;
    }

    public void setRatingDao(RatingDao ratingDao) {
        this.ratingDao = ratingDao;
    }

    public void setUserDataProfileDao(UserDataProfileDao userDataProfileDao) {
        this.userDataProfileDao = userDataProfileDao;
    }
}
